package com.hfi.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ChangLiang
 * @date 2019/5/16
 */
public class UserProxyFactory{

    private Object target;

    public UserProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        Object newProxyInstance = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
                new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                Object result = null;
                if ("save".equals(methodName)) {
                    System.out.println("userDao save方法执行前");
                    result = method.invoke(target, args);
                    System.out.println("userDao save方法执行后");
                } else {
                    result = method.invoke(target, args);
                }
                return result;
            }
        });
        return newProxyInstance;
    }
}
